package com.gengzp.permission.core.impl;

import com.gengzp.permission.core.PermissionCacheFunc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.gengzp.permission.constants.PermissionBeanNameConstants.PERMISSION_REDIS_TEMPLATE;

/**
 * @ClassName PermissionCacheCoreFuncImpl
 * @Description
 * @Author gengzp
 * @Date 2025/8/14 0:37
 */
@Component
public class PermissionCacheFuncImpl implements PermissionCacheFunc {

    @Autowired
    @Qualifier(PERMISSION_REDIS_TEMPLATE)
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public String get(String key) {
        if (key == null || key.isBlank()) {
            return null;
        }
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            return null;
        }
        return obj.toString();
    }

    @Override
    public List<String> getMultiKeys(Collection<String> keys) {
        if (keys == null || keys.isEmpty()) {
            return Collections.emptyList();
        }
        List<Object> objs = redisTemplate.opsForValue().multiGet(keys);
        if (objs == null || objs.isEmpty()) {
            return null;
        }
        return objs.stream().map(Object::toString).collect(Collectors.toList());
    }

    @Override
    public Long getExpire(String key, TimeUnit timeUnit) {
        if (key == null || key.isBlank()) {
            return null;
        }
        return redisTemplate.getExpire(key, timeUnit);
    }

    @Override
    public void set(String key, String value) {
        if (key == null || key.isBlank()) {
            return;
        }
        redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public void set(String key, String value, Long timeout, TimeUnit timeUnit) {
        if (key == null || key.isBlank()) {
            return;
        }
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    @Override
    public void del(String key) {
        if (key == null || key.isBlank()) {
            return;
        }
        redisTemplate.delete(key);
    }

    @Override
    public void del(Collection<String> keys) {
        if (keys == null || keys.isEmpty()) {
            return;
        }
        redisTemplate.delete(keys);
    }

}
